from rest_framework import serializers
from rest_framework.viewsets import ModelViewSet
from aaa import models
from django.http import JsonResponse
import json

serializers.CharField

class paramsSerializer(serializers.ModelSerializer):
    attr_sel = serializers.CharField(source='get_attr_sel_display')
    attr_write = serializers.CharField(source='get_attr_write_display')
    class Meta:
        model = models.Params
        fields = ['attr_id','cat_id','attr_name','attr_sel','attr_write','attr_vals']

class paramsView(ModelViewSet):
    '''分类参数'''
    def list(self,request,*args,**kwargs):
        print('paramsView kwargs',kwargs)
        if 'paramsId' in kwargs:
            paramsId = int(kwargs.pop('paramsId'))
            sel_dict = {'many': 0, 'only': 1}
            sel = request._request.GET.get('attr_sel')
            params_obj = models.Params.objects.get(attr_id=paramsId,attr_sel=sel_dict[sel])
            ser = paramsSerializer(instance=params_obj, many=False)
            ret = {}
            ret['data'] = json.dumps(ser.data)
            ret['meta'] = {'status':200}
            return JsonResponse(ret)
        else:
            print('else 11111111111')
            cateId = int(kwargs.pop('cateId'))
            sel_dict = {'many':0,'only':1}
            sel = request._request.GET.get('sel')
            queryset = models.Params.objects.filter(cat_id=cateId,attr_sel=sel_dict[sel])
            ser = paramsSerializer(instance=queryset,many=True)
            ret = {}
            ret['data'] = json.dumps(ser.data)
            return JsonResponse(ret)

    def post(self,request,*args,**kwargs):
        cateId = int(kwargs.pop('cateId'))
        data = request.data
        print('paramsView cateId',cateId)
        sel_dict = {'many': 0, 'only': 1}
        # obj,created = models.Role.objects.update_or_create(roleName=data['roleName'])
        # print('created',created)
        try:
            obj = models.Params.objects.filter(attr_name=data['attr_name']).first()
            print(obj)
            if not obj:
                obj = models.Params.objects.create(attr_name=data['attr_name'],
                                                   attr_sel=sel_dict[data['attr_sel']],
                                                   cat_id_id=cateId)
                obj.save()
                print(obj.id)
                return JsonResponse({'data':{'attr_name':1},'meta':{'status':201,'msg':'创建分类参数成功'}})
            return JsonResponse({'meta': {'status': 203, 'msg': '分类参数已存在!'}})
        except Exception as e:
            print(e)
            return JsonResponse({'meta':{'status':203,'msg':'获取数据异常'}})

    def put(self,request,*args,**kwargs):
        sel_dict = {'many': 0, 'only': 1}
        try:
            print('paramsView put data', request.data)
            # attr_id = int(kwargs.get('cateId'))
            paramsId = int(kwargs.get('paramsId'))
            attr_name = request.data['attr_name']
            attr_sel = sel_dict[request.data['attr_sel']]
            attr_vals = request.data['attr_vals']
            models.Params.objects.filter(attr_id=paramsId).update(attr_name=attr_name,
                                                                             attr_sel=attr_sel,
                                                                             attr_vals=attr_vals)
            ret = {'meta':{'status':200}}
        except Exception as e:
            print('put e',e)
        return JsonResponse(ret)

    def delete(self,request,*args,**kwargs):
        try:
            # attr_id = int(kwargs.get('id'))
            print('paramsView delete attr_id', kwargs)
            paramsId = int(kwargs.get('paramsId'))
            role_obj = models.Params.objects.get(attr_id=paramsId).delete()
            ret = {'meta':{'status':200}}
        except Exception as e:
            print('delete e',e)
        return JsonResponse(ret)